<template>
  <div class="app-container">
    <div class="filter-container" v-if="true">
      <el-collapse-transition>
        <div class="help">
          <div class="transition-box">
            <p>说明:</p>
            <p>1级分类可以不上传图片, 2, 3级分类需要上传图片</p>
            <p>建议最多只传3级分类</p>
          </div>
        </div>
      </el-collapse-transition>
    </div>
    <div class="filter-container">
      <el-button
        type="primary"
        icon="el-icon-circle-plus-outline"
        class="filter-item"
        size="small"
        @click="createTop"
      >添加一级分类</el-button>
    </div>
    <el-table
      :data="categoryList"
      row-key="id"
      :border="false"
      fit
      style="width: 100%;"
      :tree-props="{children: 'children'}"
    >
      <el-table-column
        prop="id"
        label="ID">
      </el-table-column>
      <el-table-column label="图片" align="center" width="100">
        <template slot-scope="{row}">
          <div class="demo-image__lazy" v-if="row.image">
            <el-image :src="row.image.thumbnail_path" lazy :fit="'cover'" :preview-src-list="[row.image.path]">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        prop="name"
        label="名称">
        <template slot-scope="{row}">
          <span>
            <el-input v-model="row.name" @change="handleName(row)" />
          </span>
        </template>
      </el-table-column>
      <el-table-column
        width="80"
        prop="sort"
        label="排序">
        <template slot-scope="{row}">
          <span>
            <el-input v-model.number="row.sort" @change="handleSort(row)" />
          </span>
        </template>
      </el-table-column>
      <el-table-column label="上传时间" prop="create_time" width="160">
        <template slot-scope="{row:{create_time}}">
          <i class="el-icon-time" />
          <span style="margin-left: 5px">{{ create_time | timeFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" prop="update_time" width="160">
        <template slot-scope="{row}">
          <i class="el-icon-time" />
          <span style="margin-left: 5px">{{ row.update_time | timeFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        width="300"
        fixed="right"
        align="right"
      >
        <template slot-scope="{ row }">
          <el-button type="success" size="mini" @click="add(row)">
            新增子类
          </el-button>
          <el-button type="primary" size="mini" @click="edit(row)">
            编辑
          </el-button>
          <el-button type="danger" size="mini" icon="el-icon-delete" @click="remove(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      :title="isEdit ? '编辑' : '添加'"
      :visible.sync="dialogVisible"
      width="50%"
      :destroy-on-close="true"
    >
      <el-form
        ref="postForm"
        :model="postForm"
        label-width="100px"
        label-suffix=":"
      >
        <el-form-item label="名称" prop="name" required>
          <el-input v-model.trim="postForm.name" />
        </el-form-item>
        <el-form-item label="图片" prop="image">
          <upload-image
            bucket="product-category"
            :max="1"
            :width="750"
            :height="750"
            :quality="50"
            @onSuccess="onSuccess"
            @onRemove="onRemove"
            :file-list="postForm.image"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="save()">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
import api from '@/api'
import { parseTime } from '@/utils'
import config from '@/config'
import UploadImage from '@/components/Upload/UploadImage'

export default {
  name: 'CategoryTree',
  components: {
    UploadImage
  },
  filters: {
    timeFilter(time) {
      return time ? parseTime(time, '{m}-{d} {h}:{i}') : ''
    },
    statusText(status) {
      return config.category.statusText(+status)
    }
  },
  data() {
    return {
      categoryList: [],
      dialogVisible: false,
      postForm: {},
      isEdit: false
    }
  },
  async mounted() {
    this.getCategoryList()
  },
  methods: {
    /**
     * 分类列表
     */
    getCategoryList() {
      api.category.getLazyCategoryTree().then(response => {
        const { data } = response
        this.categoryList = data
      })
    },
    handleName(row) {
      api.category.changeName({ ...row }).then(response => {
        this.$notify({
          title: '成功',
          message: response.message || '设置成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    handleSort(row) {
      api.category.changeSort({ ...row }).then(response => {
        this.$notify({
          title: '成功',
          message: response.message || '设置成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    handleStatus(row) {
      const status = +row.statusForm
      api.category.changeStatus({ ...row, status }).then(response => {
        this.$notify({
          title: '成功',
          message: response.message || '设置成功',
          type: 'success',
          duration: 2000
        })
        // this.handleFilter()
        row.status = status
      })
    },
    /**
     * 修改
     * @param row
     */
    edit(row) {
      this.dialogVisible = true
      this.postForm = Object.assign({}, row)
      if (row.image) {
        this.postForm.image = [
          {
            id: +row.image.id,
            url: row.image.thumbnail_path
          }
        ]
      } else {
        this.postForm.image = []
      }
      this.isEdit = true
    },
    // 创建一级分类
    createTop() {
      this.isEdit = false
      this.postForm = {
        id: 0,
        parent_id: 0,
        children: []
      }
      this.dialogVisible = true
      this.postForm.image = []
    },
    add(row) {
      this.isEdit = false
      this.postForm = {
        id: 0,
        parent_id: row.id,
        children: []
      }
      this.dialogVisible = true
      this.postForm.image = []
    },
    save() {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          // 图片
          let image = 0
          if (this.postForm.image && this.postForm.image.length > 0) {
            image = this.postForm.image.map(x => x.id)[0]
          }
          api.category.edit({
            id: this.id,
            ...this.postForm,
            image_id: image,
            parent_id: +this.postForm.parent_id
          }).then(response => {
            this.$notify({
              title: '成功',
              message: response.message || '操作成功',
              type: 'success',
              duration: 2000
            })
            // api.category.view({ id: response.data.id }).then(res => {
            //   this.actionEdit(res.data)
            // })
            this.refresh()
          }).finally(() => {
            this.dialogVisible = false
          })
        }
      })
    },
    /**
     * 删除
     * @param row
     */
    remove(row) {
      this.$confirm('您确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.category.remove({ id: row.id }).then(response => {
          this.$message({
            message: response.message || '删除成功',
            type: 'success'
          })
          // this.actionRemove(row.id)
          this.refresh()
        })
      }).catch(() => {})
    },
    refresh() {
      this.$router.push(`/product/category/tree-table?t=${new Date().getTime()}&expanded=${JSON.stringify(this.defaultExpandedKeys)}`)
    },
    /**
     * 图片上传
     */
    onSuccess(data, fileList) {
      if (data && data.id) {
        this.postForm.image.push({
          id: data.id,
          url: data.thumbnail
        })
      }
    },
    /**
     * 删除图片
     */
    onRemove(data, fileList) {
      if (data && data.id) {
        this.postForm.image = this.postForm.image.filter(x => x.id !== data.id)
      }
    }
  },
  /**
   * 刷新
   * @param to
   * @param from
   * @param next
   */
  beforeRouteUpdate(to, from, next) {
    if (to.path === from.path) {
      const newQuery = Object.assign({}, to.query)
      const oldQuery = Object.assign({}, from.query)
      if (JSON.stringify(newQuery) !== JSON.stringify(oldQuery)) {
        this.getCategoryList()
      }
    }
    next()
  }
}
</script>

<style scoped lang="scss">
.help {
  .transition-box {
    //height: 100px;
    border-radius: 4px;
    background-color: #f5f7fa;
    border: 1px solid #dfe6ec;
    color: #909399;
    padding: 10px 15px;
    box-sizing: border-box;
    text-align: left;
  }
}
</style>

